package org.lex.jdbc.url;

import java.util.ArrayList;
import java.util.List;

import org.lex.jdbc.url.parser.Fragment;
import org.lex.jdbc.url.parser.JdbcUrlTemplateParser;
import org.lex.jdbc.url.parser.OptionalFragment;
import org.lex.jdbc.url.parser.VariableFragment;

public class JdbcUrlBuilder {
	public String buildUrl(JdbcUrlTemplate template, IJdbcUrlContext context) {
		List<Fragment> list = new JdbcUrlTemplateParser().parse(template
				.getTemplate());
		StringBuilder buf = new StringBuilder();
		for (Fragment f : list) {
			buf.append(f.evaluate(context));
		}
		return buf.toString();
	}

	public List<Variable> parseVariables(String text) {
		List<Fragment> list = new JdbcUrlTemplateParser().parse(text);

		List<Variable> vars = new ArrayList<Variable>();

		for (Fragment f : list) {
			if (f instanceof VariableFragment) {
				vars.add(this.createVar(f, true));
			}

			if (f instanceof OptionalFragment) {
				OptionalFragment of = (OptionalFragment) f;
				for (Fragment cf : of.getChildren()) {
					if (cf instanceof VariableFragment) {
						vars.add(this.createVar(cf, false));
					}
				}
			}
		}
		return vars;
	}

	private Variable createVar(Fragment f, boolean required) {
		String varName = ((VariableFragment) f).getVariableName();
		Variable var = Variable.newInstance(varName, varName, "", required,
				false);
		return var;
	}
}
